package com.atguigu.yygh.common.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @FileName: JwtHelper
 * @Author Steven
 * @Date: 2021/3/26
 */
public class JwtHelper {
    /**
     * token过期时间
     */
    private static Long tokenExpiration=24*60*60*1000L;

    private static String tokenSignKey="123456";

    public static String createToken(long userId,String userName){
        String token= Jwts.builder()
                //设置主题
                .setSubject("yygh-subject")
                //设置定义的认证参数值
                .claim("userId",userId)
                .claim("userName",userName)
                //使用特定算法对签名进行加密
                .signWith(SignatureAlgorithm.HS256,tokenSignKey)
                //设置过期时间
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
                //
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)){
            return "";
        }
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }

    public static void main(String[] args) {
        String token = createToken(1001, "张三");
        Long userId = getUserId(token);
        String userName = getUserName(token);
        System.out.println(token+"----"+userId+"-----"+userName);
    }

}
